package ai.leinao.notify.webhook;

import ai.leinao.notify.core.AbstractNotifier;
import ai.leinao.notify.core.enums.NotifyType;
import ai.leinao.notify.core.template.TemplateRegistry;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;

/**
 * http 通知器
 *
 * @author zhong.wang
 * @date 2025/7/11
 */
@Getter
@Setter
public class WebHookNotifier extends AbstractNotifier<WebHookTemplate> {
    /**
     * id
     */
    private final String notifyId;

    /**
     * 配置
     */
    private final WebHookProperties properties;

    /**
     * 构造函数
     * @param properties
     * @param notifyId
     * @param templateRegistry
     */
    public WebHookNotifier(WebHookProperties properties, String notifyId, TemplateRegistry templateRegistry) {
        super(templateRegistry);
        this.notifyId = notifyId;
        this.properties = properties;
    }

    /**
     * 获取通知器ID
     *
     * @return 通知器ID
     */
    public String getNotifyId() {
        return notifyId;
    }

    /**
     * 获取通知器类型
     *
     * @return 通知器类型
     * @see NotifyType
     */
    @Override
    public NotifyType getNotifyType() {
        return NotifyType.HTTP;
    }

    /**
     * 获取通知器供应商
     *
     * @return
     */
    @Override
    public String getProvider() {
        return WebHookProviderEnum.WEBHOOK.getType();
    }

    /**
     * 指定模板{@link Template}发送消息
     * <p>
     * 不同的供应商需实现不同的发送方式
     * <p>
     *
     * @param template 模板
     * @param context  上下文
     */
    @Override
    public void send(WebHookTemplate template, Map<String, Object> context) {
        template.renderVariable(context);
        Method method = properties.getMethod();
        String url = properties.getUrl();
        String body = template.getBody();
        System.out.println(body);
        Map<String, String> headers = properties.getHeaders();

        // 创建请求
        HttpRequest request = HttpUtil.createRequest(method, url);
        if (CollUtil.isNotEmpty(headers)) {
            request.addHeaders(headers);
        }
        if(StrUtil.isNotBlank(body)){
            request.body(body);
        }
        request.execute();
    }
}
